# -*- coding: utf-8 -*-
# @author: edgardeng
# @date:   2021-05-08
# @file:   [websocket] https://websockets.readthedocs.io/en/stable/
import asyncio
import time
import sys

import websockets

now = lambda: time.time()


async def hello(msg):
    uri = "ws://localhost:8765/a"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello :" + msg)
        data = await websocket.recv()
        print(data)


# 聊天室
async def chat_demo(user):
    uri = "ws://localhost:8765/%s" % user
    async with websockets.connect(uri) as websocket:
        for i in range(3):
            data = await websocket.recv()
            print('Received', data)
            await asyncio.sleep(1)
            msg = input('please input:')
            await websocket.send(msg + " : " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
            if msg == 'exit':
                break
            await asyncio.sleep(1)
        # await websocket.send("exit")


async def hello_sanic(msg):
    uri = "ws://localhost:8000/feed"
    t0 = now()
    async with websockets.connect(uri) as websocket:
        print('use', now() - t0)
        await websocket.send("Hello :" + msg)
        data = await websocket.recv()
        print(data)
        # 短连接 只能发送一次


async def hello_sanic2(msg):
    uri = "ws://localhost:8000/feed2"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello :" + msg)
        data = await websocket.recv()
        print(data)

        await websocket.send("Hello2 :" + msg)
        data = await websocket.recv()
        print(data)

        await websocket.send('exit')


async def sanic_channel_status():
    uri = "ws://localhost:8000/channel_status"
    async with websockets.connect(uri) as websocket:
        for i in range(10):
            await websocket.send('Channel2')
            data = await websocket.recv()
            print(data)


async def sanic_channel_on():
    uri = "ws://localhost:8000/channel_on"
    async with websockets.connect(uri) as websocket:
        for i in range(10):
            await websocket.send('Channel2:ON' if i % 2 else 'Channel2:OFF')
            data = await websocket.recv()
            print(data)
            await asyncio.sleep(120)


if __name__ == '__main__':
    user = str(sys.argv[1]) if len(sys.argv) >= 2 else 'none'

    t0 = time.time()
    print('start', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t0)))
    loop = asyncio.get_event_loop()

    # task = asyncio.ensure_future(sanic_channel_status())
    loop.run_until_complete(chat_demo(user))  # 单任务

    # tasks = [asyncio.ensure_future(hello_sanic2(str(i))) for i in range(5)]
    # loop.run_until_complete(asyncio.wait(tasks)) # 多任务

    # for i in range(10):
    #     # loop.run_until_complete(hello(str(i)))
    #     loop.run_until_complete(hello_sanic(str(i)))

    t1 = time.time()
    print('end', time.strftime('%Y-%M-%D %H:%M:%S', time.localtime(t1)), t1 - t0)
